import RPi.GPIO as GPIO
from WTimer import WTimer


class LED(object):

    OFF = 0
    STEADY = 1
    FLASHING = 2

    def __init__(self, gpio_port):
        self._gpio_port = gpio_port
        self._lighted = self.STEADY
        self._speed = 0
        self._flasher = None

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self._gpio_port, GPIO.OUT)

        self.off()

    @property
    def gpio_port(self):
        return self._gpio_port

    @property
    def lighted(self):
        return self._lighted

    @property
    def lighted_real(self):
        return bool(GPIO.input(self.gpio_port))

    @property
    def speed(self):
        if self.lighted == self.FLASHING:
            return self._speed
        else:
            return None

    def _on(self):
        GPIO.output(self.gpio_port, True)

    def _flash(self):
        state = not self.lighted_real
        if state:
            self._on()
        else:
            self._off()

    def on(self, speed=0):
        self.off()

        if speed:
            self._lighted = self.FLASHING
            self._speed = speed
            self._flasher = WTimer(self._flash, self._speed)
            self._flasher.start()
        else:
            self._lighted = self.STEADY
            self._on()

    def _off(self):
        GPIO.output(self.gpio_port, False)

    def off(self):
        if not self._lighted:
            return

        if self.lighted == self.FLASHING:
            self._flasher.stop()
            self._flasher = None
            self._speed = 0
        self._lighted = self.OFF
        self._off()


def cleanup():
    GPIO.cleanup()
